package cn.edu.cqyz.wisdom.service.impl;

import cn.edu.cqyz.wisdom.entity.Collect;
import cn.edu.cqyz.wisdom.entity.R;
import cn.edu.cqyz.wisdom.entity.SessionQa;
import cn.edu.cqyz.wisdom.mapper.CollectMapper;
import cn.edu.cqyz.wisdom.mapper.SessionQaMapper;
import cn.edu.cqyz.wisdom.service.ICollectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 问答收藏表 服务实现类
 * </p>
 *
 * @author CDHong.it
 * @since 2024-12-18
 */
@Service
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements ICollectService {

    @Autowired
    public CollectMapper collectMapper;

    @Autowired
    public SessionQaMapper sessionQaMapper;

    /**
     * 收藏
     */
    @Override
    public R Collect(Collect collect) {
        SessionQa sessionQa = new SessionQa();
        sessionQa.setId(collect.getSessionQaId());
        sessionQa.setQaStar(1);
        Collect newCollect = new Collect();
        newCollect.setUserId(collect.getUserId());
        newCollect.setSessionQaId(collect.getSessionQaId());
        try {
            collectMapper.insert(newCollect);
            sessionQaMapper.updateById(sessionQa);
            return R.ok("收藏成功!");
        } catch (Exception e) {
            return R.error("网路异常!");
        }
    }

    /**
     * 取消收藏
     */
    @Override
    public R cancelCollect(Integer sessionQaId) {
        SessionQa sessionQa = new SessionQa();
        sessionQa.setId(sessionQaId);
        sessionQa.setQaStar(0);
        QueryWrapper<Collect> wrapper = new QueryWrapper<>();
        wrapper.eq("session_qa_id", sessionQaId);
        try {
            collectMapper.delete(wrapper);
            sessionQaMapper.updateById(sessionQa);
            return R.ok("取消成功!");
        } catch (Exception e) {
            return R.error("网路异常!");
        }
    }

    /**
     * 获取个人收藏总数
     * */
    @Override
    public Integer findCollectCount(Integer userId){
        QueryWrapper<Collect> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<Collect> collectList = collectMapper.selectList(wrapper);
        if(collectList.isEmpty()){
            return 0;
        }else {
            return collectList.size();
        }
    }

}
